package org.hpin.assetImport.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.xml.rpc.holders.IntegerWrapperHolder;

import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.hpin.asset.entity.Assetinfo;
import org.hpin.asset.entity.Suppliers;
import org.hpin.asset.util.Duuid;
import org.hpin.assetImport.dao.AssetImportDao;
import org.hpin.common.core.SystemConstant;
import org.hpin.common.core.orm.BaseService;
import org.hpin.common.util.DateUtils;
import org.hpin.common.util.HttpTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service(value = "org.hpin.assetImport.service.AssetImportService")
@Transactional
public class AssetImportService extends BaseService {
	@Autowired()
	private AssetImportDao dao=null;

	public int saveAssetImport(File file, String afileName) throws ParseException {
		String fileName = "";
		// 根据产品ID找出名称
		int countAll = 0;
		String saveName = System.currentTimeMillis()+ afileName.substring(afileName.lastIndexOf("."));
			if (afileName != null) {
				fileName = file.getAbsolutePath();
				long a = System.currentTimeMillis();
				InputStream is = null;
				XSSFWorkbook xssfWorkbook = null;
				try {
					is = new FileInputStream(fileName);
					xssfWorkbook = new XSSFWorkbook(is);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}catch (IOException e) {
					e.printStackTrace();
				}
				
				// 循环工作表Sheet
				XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(0);
				Date importDate = new Date();
				// 循环行Row
				
				for (int rowNum = 0; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
					XSSFRow xssfRow = xssfSheet.getRow(rowNum);
					Assetinfo assetinfo = new Assetinfo();
					if (xssfRow == null) {
						continue;
					}
					if(rowNum==0){
						List<String> titleRow = titleRow();
						for(int i = 0 ; i <= 10 ; i++ ){
							if(!getValue(xssfRow.getCell(i)).equals(titleRow.get(i))){
								return -1;
							}
						}
					}else{
						assetinfo.setModels(getValue(xssfRow.getCell(0)));
						assetinfo.setEquipnumber(getValue(xssfRow.getCell(1)));
						assetinfo.setName(getValue(xssfRow.getCell(2)));
						//Assetinfo.setType(getValue(xssfRow.getCell(3)));
						assetinfo.setProducedate(DateUtils.convertDate(getValue(xssfRow.getCell(3)),"yyyy-MM-dd"));
						
						Suppliers suppliers=(Suppliers) dao.findSupply(getValue(xssfRow.getCell(4)));
						if(dao.findSupply(getValue(xssfRow.getCell(4)))==null){
							assetinfo.setSupplyunit(null);
						}else{
							assetinfo.setSupplyunit(suppliers.getId());
						}
						//Assetinfo.setSupplyunit(suppliers.getId());
						
						assetinfo.setMoney(Integer.parseInt(getValue(xssfRow.getCell(5))));
						assetinfo.setState("1010101");
						assetinfo.setIsDeleted(0);
						
						assetinfo.setProduceunit(getValue(xssfRow.getCell(6)));
						assetinfo.setStartusetime(importDate);
						assetinfo.setUsedyears(Integer.parseInt(getValue(xssfRow.getCell(7))));
						assetinfo.setLifeyears(Integer.parseInt(getValue(xssfRow.getCell(8))));
						assetinfo.setBuyTime(DateUtils.convertDate(getValue(xssfRow.getCell(9)),"yyyy-MM-dd"));
						//Assetinfo.setDataFrom("EXCEL");
						assetinfo.setRemark(getValue(xssfRow.getCell(10)));
						countAll ++;
						dao.save(assetinfo);
						HttpTool.getRequest().setAttribute("assetInfo", assetinfo);
					}
				}
				System.out.println("耗时 :" + (System.currentTimeMillis() - a)/ 1000f + " 秒 ");
			}
			try {
				// 执行完导入后，把excel上传到服务器上
				String rootFilePath = SystemConstant.getSystemConstant("upload_root_path");
				FileOutputStream fos = null;
				
				File dir = new File(rootFilePath + "AssetImport");
				if (!dir.exists()) {
					dir.mkdir();
				}
				fos = new FileOutputStream(rootFilePath + "AssetImport" + File.separator + saveName);
				FileInputStream fis = new FileInputStream(file);
				byte[] buffer = new byte[4096];
				int len = 0;
				while ((len = fis.read(buffer, 0, 4096)) != -1) {
					fos.write(buffer, 0, len);
				}
				fos.close();
				fis.close();
			} catch (Exception e) {
				System.out.println("上传数据附件到服务器失败！");
				e.printStackTrace();
			}
		return countAll;
	}

	private String getValue(Cell cell) {
		String value = "";
		switch (cell.getCellType()) {
		case Cell.CELL_TYPE_BOOLEAN://boolean类型
			value = String.valueOf(cell.getBooleanCellValue()).trim();
			 break;
		case Cell.CELL_TYPE_NUMERIC: //数字或日期类型
			
			 if (HSSFDateUtil.isCellDateFormatted(cell)) {//判断是否是日期类型
				 value = DateUtils.DateToStr(cell.getDateCellValue(), DateUtils.DATE_FORMAT); // 把Date转换成本地格式的字符串
			}else{
				short format = cell.getCellStyle().getDataFormat();
		        SimpleDateFormat sdf = null;
		        if(format == 14 || format == 31 || format == 57 || format == 58){
		            //日期
		            sdf = new SimpleDateFormat("yyyy-MM-dd");
		            Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(cell.getNumericCellValue());
			        value = sdf.format(date);
		        }else if (format == 20 || format == 32) {
		            //时间
		            sdf = new SimpleDateFormat("HH:mm");
		            Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(cell.getNumericCellValue());
			        value = sdf.format(date);
		        }else{
		        	DecimalFormat df = new DecimalFormat("0");
		        	value = String.valueOf(df.format(cell.getNumericCellValue())).trim();
		        }
			}
			 System.out.println(HSSFDateUtil.isCellDateFormatted(cell)+"   "+value);
			break;
		case Cell.CELL_TYPE_STRING://字符类型
			value = String.valueOf(cell.getStringCellValue()).trim();
			break;
		case Cell.CELL_TYPE_BLANK://空白单元格
			break;
		default:
			value = String.valueOf(cell.getStringCellValue()).trim();
			break;
		}
		return value;
	}
	
	private List<String> titleRow(){
		List<String> list = new LinkedList<String>();
		list.add("资产型号");
		list.add("设备编号");
		list.add("设备名称");
		list.add("生产日期");
		list.add("供应商");
		list.add("购买金额");
		list.add("生产单位");
		list.add("使用年限");
		list.add("规定使用年限");
		list.add("购买日期");
		list.add("备注");
		return list;
	}

}
